package com.yz.kafka.producers;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.clients.producer.RecordMetadata;
import org.apache.kafka.common.serialization.StringSerializer;

import java.util.Properties;

/**
 * @author Administrator
 */
public class ProducerWithSerializer {
    public static void main(String[] args) {
        String topicName = "Kafka-Serializer-Test";
        Properties properties = new Properties();
        // 设置key序列号器
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class.getName());
        // 设置value序列号器（自定义对象使用自定义的序列化器）
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, CustomStudentSerializer.class.getName());
        // 设置集群地址
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "tcloud:9092");
        // 设置重试次数
        properties.put(ProducerConfig.RETRIES_CONFIG, 2);

        KafkaProducer<String, Student> producer = new KafkaProducer<>(properties);
        Student student = Student.builder().name("卡夫卡").address("郑州").build();
        ProducerRecord<String, Student> record = new ProducerRecord<>(topicName, "Student NO.1 ", student);
        try {
            /*同步发送消息*/
            RecordMetadata metadata = producer.send(record).get();
            System.out.printf("topic=%s, partition=%d, offset=%s \n", metadata.topic(), metadata.partition(), metadata.offset());
        } catch (Exception e) {
            e.printStackTrace();
        }
        producer.close();
    }
}
